﻿using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;

namespace Inlycat
{
    public class BsonConvert
    {
        public static byte[] SerializeObject(object obj)
        {
            using (var stream = new MemoryStream())
            {
                var serializer = new JsonSerializer();
                var writer = new BsonWriter(stream);
                serializer.Serialize(writer, obj);

                return stream.ToArray();
            }
        }

        public static T DeserializeObject<T>(byte[] bytes)
        {
            using (var stream = new MemoryStream(bytes))
            {
                var serializer = new JsonSerializer();
                var reader = new BsonReader(stream);
                var typeName = typeof(T).FullName;

                if (!typeName.Contains("HttpResult") && (typeName.Contains("Array") || typeName.Contains("List")))
                {
                    reader.ReadRootValueAsArray = true;
                }

                var obj = serializer.Deserialize<T>(reader);

                return obj;
            }
        }
    }
}